﻿@using Blazor.FlexGrid
@using Blazor.FlexGrid.Demo.Shared
@using Blazor.FlexGrid.DataAdapters
@using Blazor.FlexGrid.Components.Events
@using Blazor.FlexGrid.Components.Configuration

@inject HttpClient Http
@inject MasterTableDataAdapterBuilder<Customer> MasterAdapterBuilder
@inject LazyLoadedTableDataAdapter<Order> ordersAdapter
@inject BlazorComponentColumnCollection<Order> Collection

@page "/masterdetailgrid"

<h1>Customers</h1>

<GridView DataAdapter="@customersMasterDataAdapter"
          PageSize="5"
          SaveOperationFinished="@ItemSavedOperationFinished">
</GridView>

@{
    RenderFragment<Order> date = (order) => @<b>@order.OrderDate</b>;
Collection.AddColumnValueRenderFunction(o => o.OrderDate, date);
}


@code{
    CollectionTableDataAdapter<Customer> customerDataAdapter;
    CollectionTableDataAdapter<CustomerAddress> customerAddressesDataAdapter;
    MasterTableDataAdapter<Customer> customersMasterDataAdapter;

    protected override async Task OnInitializedAsync()
    {
        var customers = await Http.GetJsonAsync<Customer[]>("api/Customer/Customers");
        var customersAddresses = await Http.GetJsonAsync<CustomerAddress[]>("api/Customer/CustomersAddresses");
        customerDataAdapter = new CollectionTableDataAdapter<Customer>(customers);
        customerAddressesDataAdapter = new CollectionTableDataAdapter<CustomerAddress>(customersAddresses);

        customersMasterDataAdapter = MasterAdapterBuilder
            .MasterTableDataAdapter(customerDataAdapter)
            .WithDetailTableDataAdapter(ordersAdapter)
            .WithDetailTableDataAdapter(customerAddressesDataAdapter)
            .Build();
    }

    public void ItemSavedOperationFinished(SaveResultArgs saveResultArgs)
    {
        Console.WriteLine($"Item saved result: {saveResultArgs.ItemSucessfullySaved}");
    }
}